package com.road2trip.tools;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;


public class Translator {

	public static String translate(String in, String inLangue, String outLangue) {
		String result = null;

		String url = null;
		try {
			url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q="
					+ URLEncoder.encode(in, "UTF-8")
					+ "&langpair="
					+ URLEncoder.encode(inLangue, "UTF-8")
					+ "|"
					+ URLEncoder.encode(outLangue, "UTF-8");
			String response = sendGetRequest(url);
			System.out.println(response);
				
			try {
				JSONObject json = new JSONObject(response);
				String text = ((JSONObject)json.get("responseData")).getString("translatedText");
			    result =  org.apache.commons.lang.StringEscapeUtils.unescapeHtml(text);			    
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}						
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    System.out.println(result);
		return result;
	}

	private static String sendGetRequest(String urlString) {
		String result = null;
		try {
			URL url = new URL(urlString);
			System.out.println(url.toString());
			URLConnection conn = url.openConnection();
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
			rd.close();
			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
